package samsung.sds.survey.surveyStatistics.controller;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import samsung.sds.survey.surveyManagement.service.SurveyReleaseService;
import samsung.sds.survey.surveyStatistics.model.SurveyEntity;
import samsung.sds.survey.surveyStatistics.service.SurveyResultStatisticsService;
import samsung.sds.survey.surveyStatistics.util.SurveyStaticsUtils;
import samsung.sds.system.export.service.ExportService;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.util.*;

/**
 * @author zhang.xu
 * @createDate 2016-01-27.
 *
 * 组合统计模块
 */
@Controller
@RequestMapping("/survey/surveyStatistics/groupingStatistics")
public class GroupingStatisticsController {
    private Map<String, List<String>> excelData = new HashMap<String, List<String>>();
    @Autowired
    private SurveyResultStatisticsService surveyResultStatisticsServiceImpl;
    @Autowired
    private ExportService exportServiceImpl;
    @Autowired
    private SurveyReleaseService surveyReleaseServiceImpl;

    /**
     * 组合统计信息
     *
     * @param request
     * @param surveyId
     * @param printWriter
     * @throws IOException
     */
    @RequestMapping(value = "/statisticSurvey/{surveyId}", method = RequestMethod.POST)
    @SuppressWarnings("unchecked")
    public void statisticSurvey(HttpServletRequest request, @PathVariable String surveyId, PrintWriter printWriter) throws IOException {
        excelData.clear();
        SurveyEntity survey = surveyResultStatisticsServiceImpl.findEntityById(surveyId);
        Map<String, String[]> parameterMap = request.getParameterMap();
        Set<String> keys = parameterMap.keySet();
        List<String> staticsCom = new ArrayList<String>();
        int combineNumber = SurveyStaticsUtils.dealWithCheckedAndReturnCombineNumber(request, survey, keys, staticsCom);
        List<Map<String, String>> lastResult = generateGroupingStaticsJsonData(survey, staticsCom, combineNumber);
        String jsonString = JSON.toJSONString(lastResult);
        //替换YN类型的值变成选项
        printWriter.write(SurveyStaticsUtils.replaceKey(jsonString));
        printWriter.flush();
        printWriter.close();
    }

    /**
     * 组装成返回前台的组合统计Json串
     *
     * @param survey
     * @param staticsCom
     * @param combineNumber
     * @return
     */
    private List<Map<String, String>> generateGroupingStaticsJsonData(SurveyEntity survey, List<String> staticsCom, int combineNumber) {
        String[] array = staticsCom.toArray(new String[staticsCom.size()]);
        List<String> tempList;
        String surveyId = String.valueOf(survey.getId());
        //组合项
        tempList = SurveyStaticsUtils.combiantion(array, combineNumber);
        tempList = SurveyStaticsUtils.dealList(tempList);
        List<Map<String, String>> lastResult = new ArrayList<Map<String, String>>();
        String sql;
        Collections.reverse(tempList);
        for (int y = 0; y < tempList.size(); y++) {
            String key = tempList.get(y);
            sql = SurveyStaticsUtils.contactSql(tempList.get(y), surveyId, true);
            Map<String, String> map = new HashMap<String, String>();
            map.put("sql", sql);
            int rs = surveyResultStatisticsServiceImpl.queryVotedCountByPerGroupingStatics(map);
            Map<String, String> resultMap = new HashMap<String, String>();
            resultMap.put("key", key);
            resultMap.put("value", String.valueOf(rs));
            lastResult.add(resultMap);
        }
        putExcelData(surveyId, tempList);
        Collections.sort(lastResult, new Comparator<Map<String, String>>() {
            @Override
            public int compare(Map<String, String> o1, Map<String, String> o2) {
                if (SurveyStaticsUtils.containsAnyLetter(o1.get("value"))) {
                    return SurveyStaticsUtils.replaceSpecialStrInString(SurveyStaticsUtils.replaceSpecialKey(o1.get("value"))).compareTo(SurveyStaticsUtils.replaceSpecialStrInString(SurveyStaticsUtils.replaceSpecialKey(o2.get("value"))));
                } else {
                    return SurveyStaticsUtils.replaceSpecialStrInString(o2.get("key")).compareTo(SurveyStaticsUtils.replaceSpecialStrInString(o1.get("key")));
                }
            }
        });
        if (!StringUtils.equals(survey.getSurveyType(), SurveyStaticsUtils.YN_SURVEY_TYPE)) {
            Collections.reverse(lastResult);
        }
        return lastResult;
    }

    /**
     * 填充excel相应的data
     *
     * @param surveyId
     * @param tempList
     */
    private void putExcelData(String surveyId, List<String> tempList) {
        for (String key : tempList) {
            String sql = SurveyStaticsUtils.contactSql(key, surveyId, false);
            Map<String, String> map = new HashMap<String, String>();
            map.put("sql", sql);
            List<String> userList = surveyResultStatisticsServiceImpl.queryUserSql(map);
            excelData.put(key, userList);
        }
    }


    /**
     * 组合统计导出的方法
     *
     * @param request
     * @param response
     * @throws IOException
     * @throws IllegalArgumentException
     * @throws IllegalAccessException
     * @throws InvocationTargetException
     */
    @RequestMapping(value = "/exportController/export")
    public void exportData(HttpServletRequest request, HttpServletResponse response) throws IOException, IllegalArgumentException,
            IllegalAccessException, InvocationTargetException {
        String surveyId = request.getParameter("surveyId");
        String questionOrder = request.getParameter("selectedQuestionOrder");
        String[] questionOrderArray = questionOrder.split(",");
        SurveyEntity survey = surveyResultStatisticsServiceImpl.findEntityById(surveyId);
        int userCountBySurvey = surveyReleaseServiceImpl.queryUserCountBySurveyId(surveyId);
        int votedUserCountBySurvey = surveyReleaseServiceImpl.queryUserVotedCountBySurveyId(surveyId);
        Map<String, String> paramMap = new HashMap<String, String>();
        paramMap.put("userCountBySurvey", String.valueOf(userCountBySurvey));
        paramMap.put("votedUserCountBySurvey", String.valueOf(votedUserCountBySurvey));
        String file = exportServiceImpl.createGroupStaticSurveyStatics(excelData, survey, paramMap, questionOrderArray);
        SurveyStaticsUtils.downLoadFile(survey, request, response, file);
    }
}
